
let db = require('../utils/DB');//数据库
let to = require('../utils/await-to-js');
let { SUCCESS, ERROR } = require('../utils/result');//结果
let { HOST } = require('../utils/CONSTANT');//常量模块

//排行榜
function rankModel() {
    return async (req, res) => {
        let rst = await getRankData();
        let arr = [];//保存返回给客户端的数据
        if (rst.length > 0) {
            let ps = [];//保存promise对象
            //遍历排行榜，获取每一个排行下的销量前三的商品            
            rst.forEach(item => {
                ps.push(getHostGoods(item.thired_id));//根据三级分类id获取对应的热门商品
            });

            //执行所有的热销请求
            let [err, data] = await to(Promise.all(ps));//[[],[],[],[]]
            //遍历排行榜数据，为每一个排行榜数据新增goodList属性，保存对应的热销商品
            rst.forEach((item, index) => {
                item.goodsList = data[index];
                arr.push(item);//将构造的新的数据对象保存其阿里
            });
            // console.log(arr);
            SUCCESS(res, arr);
        } else {
            ERROR(res, '排行榜数据查询失败', err)
        }
    };
}


//获取热门分类排行榜（前四种商品）
function getRankData() {
    return db.query(`SELECT c.thired_id,c.thired_name,SUM(a.eval_start) as evalNum FROM goods_eval as a
    INNER JOIN goods_list as b ON a.goods_id=b.goods_id
    LEFT JOIN category_thired as c ON c.thired_id=b.thired_id
    GROUP BY c.thired_id
    ORDER BY evalNum DESC
    LIMIT 0,4`);
}

//获取指定分类下的热门商品(销量前三名)
function getHostGoods(id) {
    return db.query(`SELECT b.goods_id,b.goods_name,goods_price,CONCAT(?,b.image_url) as image_url,SUM(a.eval_start) as evalNum FROM goods_eval as a
    INNER JOIN goods_list as b ON a.goods_id=b.goods_id
    WHERE b.thired_id=?
    GROUP BY a.goods_id
    ORDER BY evalNum DESC
    LIMIT 0,3`, [HOST,id]);
}


module.exports = rankModel;